package sbpme.designer.parts;

import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import org.eclipse.draw2d.BendpointConnectionRouter;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.graph.CompoundDirectedGraph;
import org.eclipse.draw2d.graph.Edge;
import org.eclipse.draw2d.graph.Node;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editparts.AbstractConnectionEditPart;
import org.eclipse.gef.editpolicies.ConnectionEditPolicy;
import org.eclipse.gef.editpolicies.ConnectionEndpointEditPolicy;
import org.eclipse.gef.requests.GroupRequest;

import sbpme.designer.command.TransitionDeleteCommand;
import sbpme.designer.model.Transition;


public class TransitionPart extends AbstractConnectionEditPart implements Observer {
	
	private Observable getModelAsObservable() {
		return (Observable)getModel();
	}
	
	@Override
	public void activate() {
		if (!isActive()) {
			getModelAsObservable().addObserver(this);
			super.activate();
		}
	}
	
	@Override
	public void deactivate() {
		if (isActive()) {
			getModelAsObservable().deleteObserver(this);
			super.deactivate();
		}
	}

	public void update(Observable observable, Object argument) {
		refreshVisuals();
	}

	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.CONNECTION_ENDPOINTS_ROLE, new ConnectionEndpointEditPolicy());
		installEditPolicy(EditPolicy.CONNECTION_ROLE, new ConnectionEditPolicy() {
			protected Command getDeleteCommand(GroupRequest request) {
				return new TransitionDeleteCommand((Transition) getModel());
			}
		});
	}

	protected IFigure createFigure() {
		PolylineConnection connection = (PolylineConnection) super.createFigure();
		connection.setConnectionRouter(new BendpointConnectionRouter());
		connection.setTargetDecoration(new PolygonDecoration());
		return connection;
	}


	public void setSelected(int value) {
		super.setSelected(value);
		if (value != EditPart.SELECTED_NONE)
			((PolylineConnection) getFigure()).setLineWidth(2);
		else
			((PolylineConnection) getFigure()).setLineWidth(1);
	}

	public void contributeToGraph(CompoundDirectedGraph graph, Map map) {
		Node source = (Node) map.get(getSource());
		Node target = (Node) map.get(getTarget());
		Edge edge = new Edge(this, source, target);
		edge.weight = 2;
		graph.edges.add(edge);
		map.put(this, edge);
	}

}
